<?php

namespace app\middleware;

use app\common\ApiStatus;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class ApiRoute implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        if ($request->host(true) != API_SITE) return json(['code' => ApiStatus::API_ERROR->value, 'msg' => 'RequestID:' . md5(uniqid(mt_rand(), true))]);
        $getMethod           = ['H5' => '', 'Test' => '',];
        $request->api_method = 'post';
        $controllerClass     = $request->controller;
        $controller_name     = substr($controllerClass, strrpos($controllerClass, '\\') + 1);
        if (isset($getMethod[$controller_name])) {
            $request->api_method = 'get';
            if ($request->method() != 'GET') return json(['code' => ApiStatus::API_ERROR->value, 'msg' => 'method failed']);
        } else {
            if ($request->method() != 'POST') return json(['code' => ApiStatus::API_ERROR->value, 'msg' => 'method failed']);
        }
        return $next($request);
    }
}